#include <iostream>
#include <fcntl.h>
#include <unistd.h>
#include<cerrno>
#include<sys/stat.h>
#include<cstdio>
#include<ctime>
#include<string>
#include<sys/types.h>

#define DefaultFD -1
#define gCreater 1
#define gUser 2
#define Read O_RDONLY
#define Write O_WRONLY
#define BaseSize 4096

const std::string path = "./myfifo";
class NamedPipe
{
    bool OpenNamedPipe(int mode)
    {
        _fd = open(_fifo_path.c_str(), mode);
        if (_fd == -1)
        {
            perror("open:");
            return false;
        }
        return true;
    }

public:
    NamedPipe(const std::string &fifo_path,int who,  int fd=-1)
        : _fifo_path(fifo_path),  _fd(fd), _who(who)
    {
        if(_who==gCreater)
        {
            int res=mkfifo(_fifo_path.c_str(),0666);
            if(res!=0)
            {
                perror("mkfifo");
            }
            std::cout<<"Creater create name pipe"<<std::endl;
        }
    }

    ~NamedPipe()
    {
        if (_who == gCreater)
        {
            int res = unlink(_fifo_path.c_str());
            if (res == -1)
            {
                perror("unlink");
            }
            std::cout << "creater free named pipe" << std::endl;
        }
        if (_fd != DefaultFD)
            close(_fd);
    }
    bool OpenForRead()
    {
        return OpenNamedPipe(Read);
    }
    bool OpenForWrite()
    {
        return OpenNamedPipe(Write);
    }
    int WriteNamedPipe(const std::string &in)
    {
        return write(_fd, in.c_str(), in.size());
    }
    int ReadNamePipe(std::string *out)
    {
        char buffer[BaseSize];
        int n = read(_fd, buffer, sizeof(buffer - 1));
        if (n)
        {
            buffer[n] = 0;
            *out = buffer;
        }
        return n;
    }

private:
    const std::string _fifo_path;
    int _who;
    int _fd;
    
};
